﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web.Security;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Core.Utils;
using Elmah;
using System.Collections.Generic;

namespace Core.ScheduleTask
{
    internal static class AlbumFilesGenerator
    {
        internal static void CreateZipFile(string[] taskParameters, string appPath)
        {
            UsersRepository ur = null;
            SectionRepository sr = null;
            AlbumsRepository ar = null;

            try
            {
                ur = new UsersRepository();
                sr = new SectionRepository();
                ar = new AlbumsRepository();

                Guid uID = new Guid(taskParameters[1]);
                MembershipUser mu = Membership.GetUser(uID);

                string siteName = ConfigurationManager.AppSettings["SiteName"];
                Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);

                tSite_Photos_Album album = ar.GetAlbumByID(int.Parse(taskParameters[0]));
                tSite_Section webmasterSection = sr.GetSectionsById(8);

                if (mu != null && album != null && !string.IsNullOrEmpty(siteName) && webmasterSection != null)
                {
                    string folderToZip = appPath + ConfigurationManager.AppSettings["GalleryPath"] + album.ID.ToString("D6");
                    string folderToSave = appPath + ConfigurationManager.AppSettings["TempPath"] + uID.ToString() + "_" +  album.ID.ToString("D6") + ".zip";
                    string fileName = album.SectionName + " - " + album.Title;

                    //Create ZIP file
                    Files.GenerateZipFile(folderToZip, folderToSave, fileName);

                    // Get Mail HTML
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(siteUrl.AbsoluteUri + webmasterSection.SystemName.UppercaseFirst() + "/Mail/DownloadAlbum/" + album.ID + "/" + uID.ToString()));
                    request.Headers.Add("ScheduleTask", "true");

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        if (response != null && response.StatusCode != HttpStatusCode.NoContent)
                        {
                            string mailText = string.Empty;
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                mailText = reader.ReadToEnd();
                            }

                            string pageTitle = Mail.FetchTitleFromHTML(mailText);

                            mailText = mailText.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                            Core.Utils.Mail.SendMail(mu.Email
                                , pageTitle
                                , mailText
                                , webmasterSection.Email
                                , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }
            finally
            {
                if (ur != null)
                {
                    ur.Dispose();
                }

                if (ar != null)
                {
                    ar.Dispose();
                }

                if (sr != null)
                {
                    sr.Dispose();
                }
            }
        }

        internal static void CreateMyAlbumZipFile(string[] taskParameters, string appPath)
        {
            MyAlbumRepository mr = null;
            SectionRepository sr = null;

            try
            {
                mr = new MyAlbumRepository();
                sr = new SectionRepository();

                Guid uID = new Guid(taskParameters[0]);
                List<tSite_Photos_MyAlbum> lMyAlbum = mr.GetImagesByUserID(uID);
                tSite_Section webmasterSection = sr.GetSectionsById(8);

                // Send confirmation
                MembershipUser mu = Membership.GetUser(uID);
                string siteName = ConfigurationManager.AppSettings["SiteName"];
                Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);

                if (lMyAlbum.Count > 0 && mu != null && !string.IsNullOrEmpty(siteName) && webmasterSection != null)
                {
                    // Zip File
                    Dictionary<string, string> dImages = new Dictionary<string, string>();
                    foreach (tSite_Photos_MyAlbum picture in lMyAlbum)
                    {
                        dImages.Add(ConfigurationManager.AppSettings["GalleryPath"] + picture.AID.ToString("D6") + "/" + picture.tSite_Photos_Image.ImageName.ToString().ToLower() + ".jpg", picture.AlbumTitle);
                    }

                    byte[] baZipFolder = Files.GetZipFile(dImages, appPath);
                    string folderToSave = appPath + ConfigurationManager.AppSettings["TempPath"] + uID.ToString() + ".zip";

                    Files.ByteArrayToFile(folderToSave, baZipFolder);

                    // Get Mail HTML
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(siteUrl.AbsoluteUri + webmasterSection.SystemName.UppercaseFirst() + "/Mail/DownloadMyAlbum/0/" + uID.ToString()));
                    request.Headers.Add("ScheduleTask", "true");

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        if (response != null && response.StatusCode != HttpStatusCode.NoContent)
                        {
                            string mailText = string.Empty;
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                mailText = reader.ReadToEnd();
                            }

                            string pageTitle = Mail.FetchTitleFromHTML(mailText);

                            mailText = mailText.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                            Core.Utils.Mail.SendMail(mu.Email
                                , pageTitle
                                , mailText
                                , webmasterSection.Email
                                , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }
            finally
            {
                if (mr != null)
                {
                    mr.Dispose();
                }

                if (sr != null)
                {
                    sr.Dispose();
                }
            }
        }
    }
}
